/*
FUND EXPECTED EXCESS RETURNS 
*/
use "$datapath/Portfolio_Paper_zbar.dta", clear // average country share by funds out of country n
* us differentials
merge m:1  datem country  using "$datapath/Portfolio_Paper_Predictions.dta"

foreach v of varlist er_* {
	qui replace  `v' = 0 if country == "unitedstates"
}
drop if mi(fundid)
drop _merge

keep  datem fundid country zbar_* er_1  er_12d90 er_24d89 er_24d90 er_24d92 er_24d925 er_24d93 er_24d94 er_36d93 er_NONREC_24d94
*****************************************************************************

*****************************************************************************
*** fund weighted us differential
levelsof country, local(country)
foreach c of local country {
	qui gen sum_er_1_`c' = zbar_`c'*er_1
	qui gen sum_er_12d90_`c' = zbar_`c'*er_12d90
	qui gen sum_er_36d93_`c' = zbar_`c'*er_36d93
	qui gen sum_er_24d925_`c' = zbar_`c'*er_24d925
	qui gen sum_er_24d89_`c' = zbar_`c'*er_24d89
	qui gen sum_er_24d92_`c' = zbar_`c'*er_24d92
	qui gen sum_er_24d90_`c' = zbar_`c'*er_24d90
	qui gen sum_er_24d93_`c' = zbar_`c'*er_24d93
	qui gen sum_er_24d94_`c' = zbar_`c'*er_24d94
	qui gen sum_NONREC_`c' = zbar_`c'*er_NONREC_24d94
}
*****************************************************************************

*****************************************************************************
* reduce information and reshape the data
qui collapse (sum) sum_* , by(fundid datem)

foreach v of varlist sum_* {
	qui replace `v' = . if `v' == 0
}

qui reshape long sum_er_1_ sum_NONREC_ sum_er_12d90_ sum_er_36d93_ sum_er_24d925_  sum_er_24d89_  sum_er_24d92_ sum_er_24d93_ sum_er_24d94_ sum_er_24d90_  , i(datem fundid) j(country) string
drop if mi(sum_er_24d925_)
*****************************************************************************

*****************************************************************************
* DIFFERENTIALS

* import us differentials
merge m:1  datem country  using "$datapath/Portfolio_Paper_Predictions.dta"
foreach v of varlist er_* {
	qui replace  `v' = 0 if country == "unitedstates"
}

drop if mi(fundid)
drop _merge

* differential
qui gen z_er_1 = er_1 - sum_er_1_
qui gen z_er_24d89 = er_24d89 - sum_er_24d89_
qui gen z_er_24d89 = er_24d90 - sum_er_24d90_
qui gen z_er_24d92 = er_24d92 - sum_er_24d92_
qui gen z_er_24d925 = er_24d925 - sum_er_24d925_
qui gen z_er_24d93 = er_24d93 - sum_er_24d93_
qui gen z_er_24d94 = er_24d94 - sum_er_24d94_

qui gen z_er_12d90 = er_12d90 - sum_er_12d90_
qui gen z_er_NONREC_24d94 = er_NONREC_24d94 - sum_NONREC_
qui gen z_er_36d93 = er_36d93 - sum_36d93_

keep datem fundid country z_*

save "$datapath/Portfolio_Paper_Excessreturn.dta", replace
* end
*****************************************************************************